import React from 'react'
import { Card, Avatar, Space, Typography, Tag, Divider, Image, Upload, Form, Select, DatePicker, Input } from 'antd'
import { TrophyOutlined, CalendarOutlined, UserOutlined, UploadOutlined } from '@ant-design/icons'
import { Honor } from '../../store/honor'
import dayjs from 'dayjs'

const { Text, Title } = Typography
const { TextArea } = Input
const { Option } = Select

interface HonorCardProps {
  honor: Honor
  onClick?: () => void
  onEdit?: () => void
  onDelete?: () => void
}

const getHonorTypeColor = (type: string) => {
  switch (type) {
    case 'ACHIEVEMENT':
      return 'gold'
    case 'AWARD':
      return 'green'
    case 'RECOGNITION':
      return 'blue'
    default:
      return 'default'
  }
}

const getHonorTypeText = (type: string) => {
  switch (type) {
    case 'ACHIEVEMENT':
      return '成就'
    case 'AWARD':
      return '奖项'
    case 'RECOGNITION':
      return '荣誉'
    default:
      return type
  }
}

export const HonorCard: React.FC<HonorCardProps> = ({ 
  honor, 
  onClick, 
  onEdit, 
  onDelete 
}) => {
  const colors = {
    gold: {
      bg: 'bg-gradient-to-br from-yellow-400 to-orange-500',
      border: 'border-yellow-400',
      text: 'text-yellow-900',
    },
    green: {
      bg: 'bg-gradient-to-br from-green-400 to-teal-500',
      border: 'border-green-400',
      text: 'text-green-900',
    },
    blue: {
      bg: 'bg-gradient-to-br from-blue-400 to-indigo-500',
      border: 'border-blue-400',
      text: 'text-blue-900',
    },
    default: {
      bg: 'bg-gradient-to-br from-gray-400 to-gray-600',
      border: 'border-gray-400',
      text: 'text-gray-900',
    },
  }

  const typeColors = colors[getHonorTypeColor(honor.honorType) as keyof typeof colors] || colors.default

  return (
    <Card
      hoverable
      onClick={onClick}
      className={`${typeColors.bg} ${typeColors.text} border-2 ${typeColors.border} transition-all duration-300 hover:shadow-lg hover:scale-105`}
    >
      <div className="flex items-start gap-4">
        {/* 图标和类型标识 */}
        <div className="flex-shrink-0">
          <Avatar
            size={48}
            icon={<TrophyOutlined />}
            className={`${typeColors.bg} ${typeColors.text} border-2 ${typeColors.border}`}
            style={{ fontSize: 24 }}
          />
        </div>

        {/* 主要内容 */}
        <div className="flex-1 min-w-0">
          <Space direction="vertical" className="w-full">
            <div className="flex items-center justify-between">
              <Title level={4} className="!text-lg !font-bold !mb-0 truncate">
                {honor.title}
              </Title>
              <Tag 
                color={getHonorTypeColor(honor.honorType)}
                className="!ml-2 whitespace-nowrap"
              >
                {getHonorTypeText(honor.honorType)}
              </Tag>
            </div>

            {honor.description && (
              <Text className={`${typeColors.text} !opacity-80 line-clamp-2`}>
                {honor.description}
              </Text>
            )}

            <Divider className="!my-2" style={{ backgroundColor: typeColors.text, opacity: 0.3 }} />

            <div className="flex items-center gap-4 text-sm">
              <Space>
                <Avatar
                  src={honor.member.avatar}
                  icon={<UserOutlined />}
                  size="small"
                  className={`${typeColors.bg} ${typeColors.text}`}
                />
                <span className="font-semibold truncate" style={{ maxWidth: 100 }}>
                  {honor.member.name}
                </span>
              </Space>

              {honor.dateReceived && (
                <Space>
                  <CalendarOutlined />
                  <span>
                    {dayjs(honor.dateReceived).format('YYYY年MM月DD日')}
                  </span>
                </Space>
              )}
            </div>
          </Space>
        </div>
      </div>

      {/* 荣誉图片 */}
      {honor.imageUrl && (
        <div className="mt-4">
          <Image
            src={honor.imageUrl}
            alt={honor.title}
            className="rounded-lg w-full h-32 object-cover"
            fallback="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='200' viewBox='0 0 300 200'%3E%3Crect width='100%25' height='100%25' fill='%23e0e0e0'/%3E%3Ctext x='50%25' y='50%25' text-anchor='middle' dy='.3em' font-size='14' fill='%23999'%3E图片加载失败%3C/text%3E%3C/svg%3E"
          />
        </div>
      )}
    </Card>
  )
}

// 创建荣誉表单
export const HonorForm: React.FC<{
  honor?: Honor
  members: any[]
  onSubmit: (values: any) => void
  onCancel?: () => void
  loading?: boolean
}> = ({ honor, members, onSubmit, onCancel, loading }) => {
  const [form] = Form.useForm()

  const handleSubmit = (values: any) => {
    const submitData = {
      ...values,
      dateReceived: values.dateReceived ? values.dateReceived.format('YYYY-MM-DD') : undefined,
    }
    onSubmit(submitData)
  }

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e
    }
    return e?.fileList
  }

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      initialValues={{
        title: honor?.title,
        description: honor?.description,
        memberId: honor?.memberId,
        honorType: honor?.honorType || 'ACHIEVEMENT',
        dateReceived: honor?.dateReceived ? dayjs(honor.dateReceived) : undefined,
      }}
    >
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <Form.Item
          label="荣誉标题"
          name="title"
          rules={[{ required: true, message: '请输入荣誉标题' }]}
        >
          <Input placeholder="请输入荣誉标题" />
        </Form.Item>

        <Form.Item
          label="荣誉类型"
          name="honorType"
          rules={[{ required: true, message: '请选择荣誉类型' }]}
        >
          <Select placeholder="请选择荣誉类型">
            <Option value="ACHIEVEMENT">成就</Option>
            <Option value="AWARD">奖项</Option>
            <Option value="RECOGNITION">荣誉</Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="获得成员"
          name="memberId"
          rules={[{ required: true, message: '请选择获得荣誉的成员' }]}
        >
          <Select
            placeholder="选择成员"
            showSearch
            optionFilterProp="children"
            filterOption={(input, option: any) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {members.map((member) => (
              <Option key={member.id} value={member.id}>
                {member.name}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          label="获得日期"
          name="dateReceived"
        >
          <DatePicker className="w-full" placeholder="选择获得日期" />
        </Form.Item>
      </div>

      <Form.Item
        label="荣誉描述"
        name="description"
        rules={[{ required: true, message: '请输入荣誉描述' }]}
      >
        <TextArea
          rows={4}
          placeholder="请输入荣誉详细描述"
          maxLength={500}
          showCount
        />
      </Form.Item>

      <Form.Item
        label="荣誉图片"
        name="imageUrl"
        valuePropName="fileList"
        getValueFromEvent={normFile}
      >
        <Upload
          listType="picture-card"
          maxCount={5}
          beforeUpload={() => false}
        >
          <div>
            <UploadOutlined />
            <div style={{ marginTop: 8 }}>上传图片</div>
          </div>
        </Upload>
      </Form.Item>

      <Form.Item className="mb-0">
        <div className="flex justify-end gap-2">
          {onCancel && (
            <Button onClick={onCancel}>
              取消
            </Button>
          )}
          <Button type="primary" htmlType="submit" loading={loading}>
            {honor ? '更新' : '添加'}荣誉
          </Button>
        </div>
      </Form.Item>
    </Form>
  )
}

export default HonorCard